import axios from 'axios'
import { Message } from 'element-ui'


//缓存里存token的key
let TOKENKEY = ''
//请求头的字段放token的key
let AUTHORIZATION = ''

//请求前缀,没有则空
let base = ''



//请求拦截器
axios.interceptors.request.use(config => {

    //缓存token
    if (window.sessionStorage.getItem(TOKENKEY)) {
        config.headers[AUTHORIZATION] = window.sessionStorage.getItem(TOKENKEY)
    }
    return config
}, error => {
    console.log(error)
})

//响应拦截器，需要Element UI
axios.interceptors.response.use(success => {

    //业务逻辑
    if (success.status && success.status == 200) {

        //如有其它响应码请添加
        //业务逻辑错误
        if (success.data.code == 500 || success.data.code == 401 || success.data.code == 403) {
            Message.error({ message: success.data.message })
            return
        }

        //业务逻辑正确
        if (success.data.message) {
            Message.success({ message: success.data.message })
        }
    }
    return success.data

}, error => {
    //请求错误
    if (error.response.code == 404 || error.response.code == 504) {
        Message.error({ message: '哎呀，系统宕机了！ ε(┬┬﹏┬┬)3' })
    } else if (error.response.code == 403) {
        Message.error({ message: '权限不足，请联系管理员' })
    } else if (error.response.code == 401) {
        Message.error({ message: '尚未登录，请登录' })
    } else {
        Message.error({ message: '未知错误！' })
    }
    return
})


//Get请求
export const getResquet = (url,params) => {
    return axios({
        method:'get',
        url:`${base}${url}`,
        data:params
    })
}

//Post请求
export const postResquet = (url,params) => {
    return axios({
        method:'post',
        url:`${base}${url}`,
        data:params
    })
}

//Put请求
export const putResquet = (url,params) => {
    return axios({
        method:'put',
        url:`${base}${url}`,
        data:params
    })
}

//Delete请求
export const deleteResquet = (url,params) => {
    return axios({
        method:'delete',
        url:`${base}${url}`,
        data:params
    })
}